package model

import (
	myconn "common/conn"
	"common/helper"
	"errors"
	"time"

	"github.com/valyala/fasthttp"
	"github.com/valyala/fastjson"
)

func smsKmi(phone, code string) error {

	header := map[string]string{
		"Content-Type": "application/json",
	}
	recs := map[string]interface{}{
		"accessKey":   smsConf["kmi"]["key"],
		"secretKey":   smsConf["kmi"]["secret"],
		"to":          phone,
		"message":     smsConf["kmi"]["text"] + code,
		"callbackUrl": smsConf["kmi"]["callbackUrl"],
	}
	requestBody, _ := helper.JsonMarshal(recs)
	body, statusCode, _ := myconn.HttpDoTimeout(requestBody, "POST", smsConf["kmi"]["api"], header, time.Duration(10)*time.Second)

	if statusCode != fasthttp.StatusOK {
		return errors.New(helper.RequestFail)
	}

	var p fastjson.Parser

	v, _ := p.ParseBytes(body)
	if string(v.GetStringBytes("code")) == "200" {
		return nil
	}

	return errors.New(helper.VerificationSendErr)
}
